<template>
  <div class="add-expert">
    <el-dialog title="新增专家信息" :visible.sync="addExpertSync" :before-close="handleCloseDialog" width="80%">
      <el-card shadow="never">
        <div class="add-expert-body">
          <!--            <AddPhoto  />-->
          <div class="photoUpload">
            <el-upload
                action="#"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :onChange="onChange"
                :before-upload="beforeUpload"
                :http-request='uploadFile'
                :limit="limitCount"
                :file-list="fileList"
                :class="{styleA:fileList.length === 0,styleB:fileList.length === 1}"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog width="31%" :modal="false" :visible.sync="dialogVisible">
              <img width="500px" height="700px" :src="dialogImageUrl" alt="">
            </el-dialog>
          </div>
          <div class="messageFrom">
            <el-form label-width="100px" :model='expertInfo' :inline="true" ref="addExpertFrom"
                     :rules="addExpertFromRules">
              <el-form-item label="专家姓名:" prop="expertName">
                <el-input class="edit-expert-input" clearable placeholder="请输入专家姓名"
                          v-model="expertInfo.expertName"
                          size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="身份证号:" prop="expertIdNumber">
                <el-input class="edit-expert-input" clearable placeholder="请输入专家身份证号" maxlength="18"
                          v-model="expertInfo.expertIdNumber" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="联系方式:" prop="expertPhone">
                <el-input class="edit-expert-input" placeholder="请输入专家手机号" clearable maxlength="11"
                          v-model="expertInfo.expertPhone" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="专家性别:" prop="expertSex">
                <el-select class="edit-expert-input" placeholder="请选泽专家性别" clearable
                           v-model="expertInfo.expertSex" size="small" clearable>
                  <el-option v-for="item in sexOption" :key="item.value" :value="item.value" :label="item.label">
                    {{ item.label }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="专家分类:" prop="expertCategory">
                <el-cascader placeholder="请选泽专家分类" clearable
                             v-model="expertInfo.expertCategory"
                             :show-all-levels="false"
                             class="edit-expert-input"
                             filterable
                             :props="props"
                             size="small"
                             ref="cascaderHandle"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="联系邮箱:" prop="expertEmail">
                <el-input class="edit-expert-input" placeholder="请输入专家邮箱" clearable
                          v-model="expertInfo.expertEmail"
                          size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="最高学历:" prop="expertEducation">
                <el-input class="edit-expert-input" placeholder="请输入最高学历" clearable
                          v-model="expertInfo.expertEducation" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="专家专业:" prop="expertMajor">
                <el-input class="edit-expert-input" placeholder="请输入专家专业" clearable
                          v-model="expertInfo.expertMajor"
                          size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="专家职称:" prop="expertTitle">
                <el-select class="edit-expert-input" placeholder="请输入专家职称" clearable
                           v-model="expertInfo.expertTitle" size="small">
                  <el-option v-for="item in titleOptions" :key="item.id" :value="item.titleName" :label="item.titleName">{{item.titleName}}</el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所作地:" prop="expertRegion">
                <el-input class="edit-expert-input" placeholder="请输入专家所在地"
                          v-model="expertInfo.expertRegion" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="工作单位:" prop="expertUnit">
                <el-input class="edit-expert-input" placeholder="请输入工作单位" clearable
                          v-model="expertInfo.expertUnit"
                          size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="专家照片:" prop="expertPhoto">
                <el-input class="edit-expert-input" placeholder="请选择专家照片" clearable
                          v-model="expertInfo.expertPhoto" size="small" disabled></el-input>
              </el-form-item>
            </el-form>
          </div>

        </div>
        <VueEditor maxLength="2000" placeholder="请输入专家简介..." class="editor"
                   v-model="expertInfo.expertIntroduce" :editorToolbar="customToolbar"/>
      </el-card>
      <div class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddExpertInfo(null)">确认添加</el-button>
        <el-button type="success" @click="handleAddExpertInfo(false)">保存并再次添加</el-button>
        <div class="info">添加成功后，手机号为登录账号,密码为身份证后六位</div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import store from '@/store'
import { mapState } from 'vuex'
import { VueEditor,Quill } from 'vue2-editor'
import { GetCategoryByParentAndLevelApi } from '@/request/category/category-api'
import { uploadPhotoApi } from '@/request/common/photo-api'
import { validateAddUserIdNumber, validateAddUserPhone } from '@/utils/validate/add-user-validate'
import { addExpertInfoApi } from '@/request/expert/expert-api'
import { GetAllTitleApi } from '@/request/title/title-api'
let fontList = ['SimSun','宋体','楷体','黑体','幼圆']
Quill.imports['formats/font'].whitelist = fontList
Quill.register(Quill.imports['formats/font'])

let fontSizeList = [false, '10px','12px','14px','16px','20px','24px']
Quill.imports['attributors/style/size'].whitelist = fontSizeList
Quill.register(Quill.imports['attributors/style/size'])
export default {
  components: {
    VueEditor
  },
  created () {
    this.initTitle()
    },
  computed: {
    ...mapState({
      addExpertSync: state => state.ExpertEdit.addExpertSync
    })
  },
  data () {
    return {
      sexOption: [{
        'value': 1,
        'label': '男'
      }, {
        'value': 0,
        'label': '女'
      }],
      fileList: [],
      dialogVisible: false,
      limitCount: 1,
      dialogImageUrl: '',
      isSelectNotBindUser: false,
      expertInfo: {
        expertPhoto: null,
        expertName: null,
        expertSex: null,
        expertPhone: null,
        expertIdNumber: null,
        expertEmail: null,
        expertEducation: null,
        expertMajor: null,
        expertTitle: null,
        expertRegion: null,
        expertUnit: null,
        expertCategory: null,
        expertIntroduce: null,
        expertUser: null
      },
      customToolbar: [
        [{ size: fontSizeList }],
        [{ font: fontList }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //几级标题
        ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
        ['blockquote', 'code-block'], //引用，代码块
        [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
        [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
        [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
        [{ 'direction': 'rtl' }], // 文本方向
        [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
        // [{'font': []}], //字体
        [{ 'align': [] }], //对齐方式
        ['clean'], //清除字体样式
        // ['image', 'video'] //上传图片、上传视频
      ],
      titleOptions:null,
      props: {
        lazy: true,
        checkStrictly: true,
        async lazyLoad (node, resolve) {

          let { level } = node
          //调用接口
          let res = await GetCategoryByParentAndLevelApi(node.value ? node.value : 0, level)
          if (res) {
            const nodes = res.data.map(item => (
                {
                  value: item.id,
                  label: item.categoryCode + ' ' + item.categoryName,
                  leaf: level >= 2
                }
            ))
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes)
          }
        }
      },
      addExpertFromRules: {
        expertName: {
          required: true,
          message: '请输入专家姓名',
          trigger: 'blur'
        },
        expertIdNumber: [{
          required: true,
          message: '请输入身份证号',
          trigger: 'blur'
        }, {
          validator: validateAddUserIdNumber,
          trigger: 'blur'
        }],
        expertPhone: [{
          required: true,
          message: '请输入联系方式',
          trigger: 'blur'
        }, {
          validator: validateAddUserPhone,
          trigger: 'blur'
        }],

        expertSex: {
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        },
        expertCategory: {
          required: true,
          message: '请选泽专家分类',
          trigger: 'blur'
        },
        expertEmail: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱',
          trigger: 'blur'
        }],
        expertEducation: {
          required: true,
          message: '请输入最高学历',
          trigger: 'blur'
        },
        expertMajor: {
          required: true,
          message: '请输入专业',
          trigger: 'blur'
        },
        expertTitle: {
          required: true,
          message: '请输入专家职称',
          trigger: 'blur'
        },
        expertRegion: {
          required: true,
          message: '请输入所在地',
          trigger: 'blur'
        },
        expertUnit: {
          required: true,
          message: '请输入工作单位',
          trigger: 'blur'
        },
        expertPhoto: {
          required: true,
          message: '请上传专家照片',
          trigger: 'blur'
        },

      }
    }
  },
  methods: {
    // 重置表单内容
    resetAddExpertFrom () {
      this.fileList = []
      this.dialogVisible = false
      this.limitCount = 1
      this.dialogImageUrl = ''
      this.expertInfo = {
        expertPhoto: null,
        expertName: null,
        expertSex: null,
        expertPhone: null,
        expertIdNumber: null,
        expertEmail: null,
        expertEducation: null,
        expertMajor: null,
        expertTitle: null,
        expertRegion: null,
        expertUnit: null,
        expertCategory: null,
        expertIntroduce: null,
        expertUser: null
      }
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addExpertFrom'].clearValidate()
      })
    },
    //点击上传文件触发的额外事件,清空fileList
    delFile () {
      this.fileList = []
    },
    //自定义上传文件
    async uploadFile (val) {
      var file = new FormData()
      file.append('file', val.file)
      let res = await uploadPhotoApi(file)
      if (res.code === 200) {
        this.$message.success('上传成功')
        this.expertInfo.expertPhoto = res.data
      }
    },
    //删除文件
    handleRemove (file, fileList) {
      this.fileList = []
      this.expertInfo.expertPhoto = null
    },
    onChange (file, fileList) {
      this.fileList = fileList
    },
    beforeUpload (file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 5
        if (['png', 'jpeg', 'jpg', 'PNG', 'JPG', 'JPEG', 'gif', 'GIF'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.fileList = []
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 5MB!')
          return false
        }
        return file
      }
    },
    async initTitle () {
      let res = await GetAllTitleApi()
      if (res&&res.code===200){
          this.titleOptions=res.data
      }
    },
    // 点击文件
    handlePreview (file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    close () {
      this.resetAddExpertFrom()
      store.commit('ExpertEdit/changeAddExpertSync', false)
    },
    handleAddExpertInfo (isContinueAdd) {
      this.$refs.addExpertFrom.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          this.$confirm('确定添加该专家信息吗？', '提示',
              {
                'confirmButtonText': '确定',
                'cancelButtonText': '取消',
                'type': 'warning'
              }).then(async () => {
            this.expertInfo.expertCategory = this.expertInfo.expertCategory[this.expertInfo.expertCategory.length-1]
            let res = await addExpertInfoApi(this.expertInfo)
            if (res.code === 200) {
              this.$message.success('添加专家信息成功')
              await this.$parent.expertInit()
              //更新初始数据
              this.resetAddExpertFrom()
              if (!isContinueAdd) {
                this.close()
              }
            } else {
              this.$message.error(res.msg)
            }
          }).catch((e) => {
            if (e === 'cancel') {
              this.$message.info('取消添加')
            } else {
              this.$message.error('未知错误！')
            }
          })
        }
      })
    },
    handleCloseDialog () {
      this.$confirm('确定取消添加专家信息吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(() => {
        this.close()
      }).catch((e) => {
        if (e === 'cancel') {
          if (e === 'cancel') {
          }
        }
      })
    }
  }
}
</script>
<style lang="less">
.el-cascader-panel {
  max-height: 300px !important;
}

.styleA .el-upload--picture-card {
  width: 110px;
  height: 110px;
  line-height: 110px;
}

.styleB .el-upload--picture-card {
  display: none;
}

</style>
<style scoped lang="less">
.add-expert {
  .el-dialog {
    .el-card {
      margin: 0 auto;

      .add-expert-body {
        margin: 10px 100px;
        display: flex;
        justify-items: auto;

        .edit-expert-input {
          width: 200px;
        }
      }
    }

    .dialog-footer {
      margin: 0 auto;
      padding: 20px 20px;
      max-width: 340px;

      .info {
        color: red;
        margin-top: 10px;
      }
    }
  }
}

.photoUpload {
  margin-right: 100px;
}

/deep/ .el-dialog {
  border-radius: 10px;
  margin-top: 80px !important;
}

.editor {
  /deep/ .ql-container {
    overflow-y: scroll;
    max-height: 180px !important;
  }
}

.submit-button {
  width: 150px;
  margin-top: 10px;
}

/deep/ .el-upload-list__item, /deep/ .el-upload {
  width: 150px !important;
  height: 210px !important;
}

/deep/ .el-icon-plus {
  margin-top: 80px !important;
}

.updateButton {
  margin-top: 5px;
  width: 150px;
}

</style>
